package com.dayu.finecomm.aop;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dayu.finecomm.aop.adapt.mongo.AopFields;
import com.dayu.finecomm.aop.adapt.mongo.AopMongoAdapt;

/**
 * AOP日志记录接受，并保存于数据库
 * 
 * @author XuJialiang
 * @since 2017-11-10 14:45:12
 * @version V1.0.0
 */
@Service
public class AopLogService implements Runnable {

	static Logger LOGGER = LoggerFactory.getLogger(AopLogService.class);

	@Autowired
	AopMongoAdapt mMongoAdapt;

	private BlockingQueue<AopLogItem> mLogQueue = null;

	public AopLogService() {
		LOGGER.info("AopLogService constructor");
	}

	public void start(BlockingQueue<AopLogItem> queue) {
		mLogQueue = queue;

		ScheduledExecutorService service = Executors
				.newSingleThreadScheduledExecutor();
		service.scheduleAtFixedRate(this, 1000, 50, TimeUnit.MILLISECONDS);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			int count = mLogQueue.size();

			while (0 != count-- && false == mLogQueue.isEmpty()) {
				AopLogItem item = mLogQueue.poll(50, TimeUnit.MILLISECONDS);

				if (null != item) {
					AopFields record = new AopFields();

					record.setLevel(item.level);
					record.setName(item.name);
					record.setPath(item.path);
					record.setArgs(item.args);
					record.setResult(item.result);
					record.setReqTime(item.reqTime);
					record.setRspTime(item.rspTime);
					record.setConsume(item.consume);

					mMongoAdapt.insert(record);
				}
			}
		} catch (Exception e) {
			LOGGER.error("Save aop log failed: " + e);
		}
	}
}
